package user

import (
	"context"

	"mydemo/api/rewark/internal/model"
	"mydemo/api/rewark/internal/svc"
	"mydemo/api/rewark/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginInput) (resp *types.UserLoginOutput, err error) {
	out := &types.UserLoginOutput{
		Code: 400,
		Msg:  "失败",
	}
	userDao := &model.User{
		Name:     req.Name,
		Password: req.PassWord,
	}
	db := l.svcCtx.Db
	var sqlErr error
	db.Transaction(func(db *gorm.DB) error {
		if err := userDao.Add(db); err != nil {
			sqlErr = err
			return err
		}
		return nil
	})
	if sqlErr != nil {
		return out, sqlErr
	}
	out.Msg = "账号创建成功"
	out.Code = 200
	out.Data = types.UserLogin{
		Id:     uint(userDao.Id),
		Name:   userDao.Name,
		Gender: userDao.Gender,
	}
	return out, nil
}
